<?php
/**
 * 加解密相关
 * 
 * @package util
 * @author wangzhiliang
 */
class MCrypt
{
    # 向量
    const TRIPLEDESIV = '0102030405060708';
    # 密钥
    const TRIPLEDESKEY = '201003181405ABCDEF201003181405ABCDEF201003181405';
    /**
     * 3DES Encrypt
     * 
     * @param mix $input 
     * @return binary data
     */
    static public function tripleDESEncrypt ($input)
    {
        $key = pack('H48', self::TRIPLEDESKEY);
        $iv = pack('H16', self::TRIPLEDESIV);
        return mcrypt_encrypt(MCRYPT_3DES, $key, self::PaddingPKCS7($input), MCRYPT_MODE_CBC, $iv);
    }
    /**
     * 3DES Decrypt
     * 
     * @param binary $input
     * @return mix
     */
    static public function tripleDESDecrypt ($input)
    {
        $key = pack('H48', self::TRIPLEDESKEY);
        $iv = pack('H16', self::TRIPLEDESIV);
        $result = mcrypt_decrypt(MCRYPT_3DES, $key, $input, MCRYPT_MODE_CBC, $iv);
        $end = ord(substr($result, - 1));
        $out = substr($result, 0, - $end);
        return $out;
    }
    /**
     * 补位，兼容Java C#
     * 
     * @param string $input
     * @return string
     */
    private function PaddingPKCS7 ($input)
    {
        $srcdata = $input;
        $block_size = mcrypt_get_block_size('tripledes', 'ecb');
        $padding_char = $block_size - (strlen($input) % $block_size);
        $srcdata .= str_repeat(chr($padding_char), $padding_char);
        return $srcdata;
    }
}